<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>table模块快速使用</title>
    <link rel="stylesheet" href="../static/layui-v2.6.4/layui/css/layui.css">
</head>
<body>


<div class="layui-card">
    <div class="layui-card-body">
        <form class="layui-form" action="">
            <div class="layui-form-item">
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">文章名</label>
                    <div class="layui-input-inline">
                        <input type="text" name="title" placeholder="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">分类</label>
                    <div class="layui-input-inline">
                        <input type="text" name="categories" placeholder="" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item layui-inline">
                    <label class="layui-form-label">时间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="created" placeholder="" class="layui-input" id="search_created">
                    </div>
                </div>

                <div class="layui-form-item layui-inline">
                    <button class="layui-btn" lay-submit lay-filter="artical-query">
                        <i class="layui-icon layui-icon-search"></i>
                        查询
                    </button>
                    <button type="reset" class="layui-btn">
                        <i class="layui-icon layui-icon-refresh"></i>
                        重置
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<table id="demo" lay-filter="test"></table>

<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
        <button class="layui-btn layui-btn-sm" lay-event="delete">删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="update">编辑</button>
    </div>
</script>

<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-primary  layui-btn-xs" lay-event="detail">查看</a>

    <button type="button" class="layui-btn layui-btn-sm" lay-event="modify">
        <i class="layui-icon">&#xe642;</i>
    </button>
    <button type="button" class="layui-btn layui-btn-sm" lay-event="delete">
        <i class="layui-icon">&#xe640;</i>
    </button>

    <!--<a class="layui-btn layui-btn-xs" lay-event="modify">编辑</a>-->
    <!--<a class="layui-btn layui-btn-danger layui-btn-radius layui-btn-xs" lay-event="delete">删除</a>-->
</script>


<div id="detail" style="display: none">
    <div class="layui-form-item">
        <label class="layui-form-label">文章名</label>
        <label class="layui-form-label" id="title" style="width: auto;background-color: #00FF00"></label>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">简介</label>
        <label class="layui-form-label" id="content" style="width: auto"></label>

    </div>

</div>


<div id="modifyPage" style="display: none">
    <form class="layui-form" action="">

        <input type="hidden" name="id" id="id_modify" required lay-verify="required" placeholder="请输入标题"
               autocomplete="off" class="layui-input">
        <div class="layui-form-item">
            <label class="layui-form-label">输入框</label>
            <div class="layui-input-block">
                <input type="text" name="title" id="title_modify" required lay-verify="required" placeholder="请输入标题"
                       autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">日期</label>
            <div class="layui-input-inline">
                <input type="text" name="created" id="created_modify" class="layui-input">
            </div>

        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">爱好</label>
            <div class="layui-input-block">
                <select name="hobby" lay-filter="aihao" id="hobby_modify">
                    <option value=""></option>
                    <option value="0">写作</option>
                    <option value="1" selected="">阅读</option>
                    <option value="2">游戏</option>
                    <option value="3">音乐</option>
                    <option value="4">旅行</option>
                </select>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-input-block">
                <button class="layui-btn" lay-submit lay-filter="updateDemo">立即提交
                </button>
                <button type="reset" class="layui-btn layui-btn-primary">重置</button>
            </div>
        </div>
    </form>


</div>

<script>
    //Demo
    layui.use('form', function () {
        var form = layui.form;

        //监听提交
        form.on('submit(formDemo)', function (data) {
            layer.msg(JSON.stringify(data.field));
            return false;
        });
    });
</script>

<script src="../static/layui-v2.6.4/layui/layui.js"></script>
<script>
    layui.use('table', function () {
        var table = layui.table
            , layer = layui.layer
            , $ = layui.jquery
            , laydate = layui.laydate
            , form = layui.form;

        //第一个实例
        table.render({
            elem: '#demo'
            , height: 312
            , url: '/getArticlePageList' //数据接口
            ,method:'post'
            , page: true //开启分页
            , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            //,toolbar: '#toolbarDemo'
            ,limit:4
            , limits: [4, 8, 12]
            , cols:
                [
                    [ //表头
                        {type: 'checkbox', fixed: 'left'}
                        , {field: 'id', title: 'ID', width: 80, fixed: 'left'}
                        , {field: 'title', title: '文章名'}
                        , {field: 'content', title: '内容', sort: true}
                        , {
                        field: 'created',
                        title: '创建时间',
                        templet: "<div>{{layui.util.toDateString(d.created, 'yyyy-MM-dd')}}</div>"
                    }
                        , {field: 'categories', title: '分类'}
                        , {field: 'tags', title: '不知道', sort: true}
                        , {fixed: 'right', align: 'center', toolbar: '#barDemo'}
                    ]
                ]
        });


        laydate.render({
            elem: "#created_modify"
        })

        laydate.render({
            elem: "#search_created"
        })

        //监听头工具栏事件
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id)
                , data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'add':
                    layer.msg('添加');
                    break;
                case 'update':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else if (data.length > 1) {
                        layer.msg('只能同时编辑一个');
                    } else {
                        layer.alert('编辑 [id]：' + checkStatus.data[0].id);
                    }
                    break;
                case 'delete':
                    if (data.length === 0) {
                        layer.msg('请选择一行');
                    } else {
                        layer.msg('删除');
                        var ids = new Array();
                        for (var i = 0; i < checkStatus.data.length; i++) {
                            ids.push(checkStatus.data[i].id);
                        }
                        console.log(ids);
                        var data = {"ids": ids}
                        $.ajax({
                            url: "/delArticleByIds",
                            data: data,
                            traditional: true,//用传统方式序列化数据
                            success: function (d) {
                                console.log(d.data)
                                table.reload('demo')
                            }
                        })

                    }
                    break;
            }
            ;
        });

        var index
        //监听行工具事件
        table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'detail') {
                //Ajax获取
                $.get('getArticleById/' + data.id, {}, function (d) {
                    layer.open({
                        type: 1,
                        offset: 'r',
                        anim: 4,
                        area: ['500px', '500px'],
                        content: $('#detail')
                        //"文章名：" + d.data.title + "/n 文章内容" + d.data.content //注意，如果str是object，那么需要字符拼接。
                    });
                    $("#title").text(d.data.title);
                    $("#content").text(d.data.content);
                });
            } else if (layEvent === 'modify') {
                //Ajax获取
                $.get('getArticleById/' + data.id, {}, function (d) {
                    console.log(JSON.stringify(d));
                    index = layer.open({
                        type: 1,
                        area: ['500px', '500px'],
                        content: $('#modifyPage')
                        //"文章名：" + d.data.title + "/n 文章内容" + d.data.content //注意，如果str是object，那么需要字符拼接。
                    });
                    $("#title_modify").val(d.data.title);
                    //将date时间对象转换成格式为yyyy-MM_dd   date---->String
                    var toDateString = layui.util.toDateString(d.data.created, "yyyy-MM-dd");
                    $("#created_modify").val(toDateString);
                    $("#id_modify").val(d.data.id);//给隐藏域id主键赋值
                    $("#hobby_modify").val(d.data.hobby);
                    form.render('select');
                });
            } else if (layEvent === 'delete') {
                $.ajax({
                    url: "/delArticleById/" + data.id,
                    type: "get",
                    success: function (d) {
                        var re = d.data;
                        if (re > 0) {

                            //window.location.href = "/list";
                            table.reload('demo', {
                                where: { //设定异步数据接口的额外参数，任意设

                                }
                                , page: {
                                    curr: 1 //重新从第 1 页开始
                                }
                            }); //只重载数据
                            layer.msg("删除成功");
                        }
                        else {
                            layer.msg("删除失败")
                        }
                    }
                })
            }
        });


        //监听提交
        form.on('submit(updateDemo)', function (data) {
            // var like = [];
            // $('input[name=like]:checked').each(function () {
            //     like.push($(this).val());
            // });
            // data.field.like = like;
            console.log(data.field);
            data.field.created = new Date(data.field.created);
            console.log(data.field);
            $.ajax({
                url: "/updArticleById",
                data: data.field,
                dataType: "json",
                type: "POST",
                success: function (d) {
                    if (d.data > 0) {
                        layer.close(index);
                        table.reload("demo")
                    }
                    // console.log(d)
                    // document.getElementById("msg").innerText = d.msg;
                    // window.location.href = '/test'
                }
            })
            return false;
        });


        form.on('submit(artical-query)', function (data) {
            if (data.field.created != "") {
                data.field.created = new Date(data.field.created);
            } else {
                delete data.field.created;
            }
            data.field.page=1;
            data.field.limit=4;
            console.log(JSON.stringify(data.field))
            $.ajax({
                url: "/getArticlePageList",
                data: data.field,
                dataType: "json",
                type: "POST",
                success: function (d) {
                    table.reload('demo', {
                        where: { //设定异步数据接口的额外参数，任意设
                            title: data.field.title
                            ,created:  data.field.created,
                            categories: data.field.categories
                        }
                        ,page: {
                            curr: 1 //重新从第 1 页开始
                        }
                    }); //只重载数据
                }
            })
            return false;
        });


    });
</script>
</body>
</html>